<template>
  <el-form v-show="visible" label-width="100px">
    <el-form-item label="属性名">
      <el-input
        type="text"
        placeholder="请输入属性名"
        v-model="spuInfo.spuName"
      ></el-input>
    </el-form-item>

    <el-form-item label="spu品牌">
      <el-select v-model="spuInfo.tmId" placeholder="请选择">
        <el-option
          :label="trademark.tmName"
          :value="trademark.id"
          v-for="trademark in trademarkList"
          :key="trademark.id"
        ></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="spu描述">
      <el-input
        type="textarea"
        rows="4"
        placeholder="请输入spu"
        v-model="spuInfo.description"
      ></el-input>
    </el-form-item>

    <el-form-item label="spu图片">
      <el-upload
        :file-list="imgList"
        action="/dev-api/admin/product/fileUpload"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <i class="el-icon-plus"></i>
      </el-upload>
      <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="" />
      </el-dialog>
    </el-form-item>
    <!-- `有${viewAttrlist.length}可选属性` -->
    <el-form-item label="销售属性">
      <el-select
        v-model="attrOrName"
        :placeholder="`${
          viewAttrlist.length > 0
            ? `有${viewAttrlist.length}个属性可选`
            : '啦拉辣啦'
        }`"
        @change="addAttrInfo"
      >
        <el-option
          :label="attr.name"
          :value="attr.id + ':' + attr.name"
          v-for="attr in viewAttrlist"
          :key="attr.id"
        ></el-option>
      </el-select>
      <el-button type="primary" icon="el-icon-plus">添加销售属性</el-button>
    </el-form-item>

    <el-form-item>
      <el-table
        :data="spuInfo.spuSaleAttrList"
        style="width: 100%; margin-bottom: 20px"
        border
      >
        <el-table-column type="index" label="序号" align="center" width="80">
        </el-table-column>
        <el-table-column prop="saleAttrName" label="属性名"> </el-table-column>
        <el-table-column label="属性值列表" prop="spuSaleAttrValueList">
          <template slot-scope="{ row }">
            <el-tag
              :key="spuSale.id"
              v-for="(spuSale, index) in row.spuSaleAttrValueList"
              closable
              :disable-transitions="false"
              @close="handleClose(row.spuSaleAttrValueList, index)"
            >
              {{ spuSale.saleAttrValueName }}
            </el-tag>
            <el-input
              class="input-new-tag"
              v-if="row.edit"
              v-model="row.saleAttrValueName"
              ref="saveTagInput"
              size="small"
              @keyup.enter.native="$event.target.blur"
              @blur="handleInputConfirm(row)"
            >
            </el-input>
            <el-button
              v-else
              class="button-new-tag"
              size="small"
              @click="showInput(row)"
              >+ 添加</el-button
            >
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="{ $index }">
            <el-button
              icon="el-icon-delete"
              size="mini"
              type="danger"
              @click="deleteSaleAttr($index)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="saveSpuInfo">保存</el-button>
      <el-button @click="handler">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
let i = 0;
export default {
  name: "SpuForm",
  props: ["visible"],
  data() {
    return {
      attrOrName: [],
      dialogImageUrl: "",
      dialogVisible: false,
      spuId: "",
      trademarkList: [],
      imgList: [],
      spuInfo: {
        spuName: "",
        description: "",
        category3Id: "",
        tmId: "",
        spuSaleAttrList: [],
        spuImageList: [],
      },
      attrList: [],

      // dynamicTags: ["标签一", "标签二", "标签三"],
      inputVisible: false,
      inputValue: "",
    };
  },
  computed: {
    viewAttrlist() {
      return this.attrList.filter(
        (a) =>
          !this.spuInfo.spuSaleAttrList.some((b) => a.name == b.saleAttrName)
      );
    },
  },
  methods: {
    repeatData() {
      this.spuId = ""; // spuId数据
      this.spuInfo = {
        spuName: "", // 名字
        tmId: "", // 品牌的id
        description: "", // 描述信息
        category3Id: "", // 三级分类的id
        spuImageList: [], // 图片列表数据
        spuSaleAttrList: [], // 销售属性数据
      };
      this.trademarkList = []; // 品牌列表数据
      this.attrList = []; // 所有的销售属性数据
      this.imgList = []; // spuInfo对象中所有的图片列表数据

      this.dialogImageUrl = ""; // 预览图片地址
      this.dialogVisible = false; // 是否开启预览效果
      this.attrIdOrAttrName = ""; // 用来存储选中的销售属性的id和名字
    },
    handler() {
      console.log(11);
      this.$emit("update:visible", false);
    },
    //移除图片的方法
    handleRemove(file, fileList) {
      this.attrList = fileList;
    },
    //设置图片预览效果
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 图片上传成功了,图片的地址应该重新的保存一下
    handleAvatarSuccess(res, file, fileList) {
      this.imgList = fileList;
    },
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg'
      const isJPGOrPNG = ["image/jpeg", "image/png"].includes(file.type);
      // 限制图片的大小,不能超过2M
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPGOrPNG) {
        this.$message.error("上传图片只能是 JPG/PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isJPGOrPNG && isLt2M;
    },
    UpdateData(spuId) {
      this.spuId = spuId;
      this.getSpuInfoById();
      this.getTrademarkLists();
      this.getSaleAttrList();
      this.getImageList();
    },
    async getSpuInfoById() {
      let result = await this.$api.spu.getSpuById(this.spuId);
      this.spuInfo = result.data;
    },
    async getTrademarkLists() {
      let result = await this.$api.trademark.getTrademarkList();
      this.trademarkList = result.data;
    },
    async getSaleAttrList() {
      let result = await this.$api.spu.getBaseSaleAttrList();
      this.attrList = result.data;
    },
    async getImageList() {
      let result = await this.$api.sku.getSpuImageList(this.spuId);
      let imgList = result.data;
      imgList.forEach((item) => {
        item.name = item.imgName;
        item.url = item.imgUrl;
      });
      this.imgList = imgList;
    },
    handleClose(spu, index) {
      spu.splice(index, 1);
    },
    showInput(attr) {
      console.log(attr);
      if (!attr.hasOwnProperty("edit")) {
        this.$set(attr, "edit", true);
      } else {
        attr.edit = true;
      }

      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm(attr) {
      const saleAttrValueName = attr.saleAttrValueName;
      if (!saleAttrValueName || !saleAttrValueName.trim()) {
        this.$message.warning("请输入有效数据");
        attr.edit = false;
        return;
      }
      const isRepeat = attr.spuSaleAttrValueList.some(
        (item) => item.saleAttrValueName === saleAttrValueName.trim()
      );
      if (!isRepeat) {
        attr.spuSaleAttrValueList.push({
          baseSaleAttrId: attr.baseSaleAttrId,
          saleAttrValueName,
        });
      } else {
        this.$message.error("请勿重复提交");
      }
      attr.edit = false;
      attr.saleAttrValueName = "";
    },
    addAttrInfo() {
      console.log(this.attrOrName);
      const attrOrName = this.attrOrName;
      if (!attrOrName) {
        this.$message.warning("请输入一个销售属性");
        return false;
      }
      console.log(attrOrName);
      const [baseSaleAttrId, saleAttrName] = attrOrName.split(":");
      this.spuInfo.spuSaleAttrList.push({
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: [],
      });
      this.attrOrName = "";
    },
    deleteSaleAttr(index) {
      this.spuInfo.spuSaleAttrList.splice(index, 1);
    },
    //保存数据
   async saveSpuInfo() {
      // console.log(this.spuInfo)
      // console.log(this.imgList)
      const { spuSaleAttrList } = this.spuInfo;
      this.spuInfo.spuSaleAttrList = spuSaleAttrList.filter((item) => {
        if (item.spuSaleAttrValueList.length > 0) {
          delete item.edit;
          delete item.saleAttrValueName;
          return true;
        }
      });
      this.spuInfo.spuImageList = this.imgList.map((item) => {
        return {
          imgName: item.name,
          imgUrl: item.response ? item.response.data : item.imgUrl,
        };
      });
      console.log(this.spuInfo);
      let result = await this.$api.spu.saveOrChangeSpuInfo(this.spuInfo)
      if(result.code == 200){
          this.$message.success('添加成功')
          this.handler()
          this.$emit('success')
      }else{
          this.$message.error('添加失败')
      }
    },
    addData(id3){
        this.spuInfo.category3Id = id3
        this.getTrademarkLists()
        this.getSaleAttrList()
    },
    
  },
};
</script>

<style >
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>